﻿using HomeCareLibrary.AppService;
using HomeCareLibrary.Constants;
using HomeCareLibrary.Core.DataContracts;
using HomeCareLibrary.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;

namespace HomeCareLibrary.Controllers
{
    public class HomeController : BaseController
    {
        private homewizard_test2databaseEntities db = new homewizard_test2databaseEntities();
         
        public ActionResult Index()
        {

            //Session[SessionConstants.MODE] = ApplicationModeConstants.IPHONE_APP;
            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            //Session[SessionConstants.PROMO_CODE] = 123;

            var model = new HomeCareLibraryCategoryModel();

            model.listPortfolio = (from p in db.HomeCareLibraryCategories
                                   select new HomeCareLibraryCategoryModel()
                                   {
                                       ID = p.ID,
                                       HomeCare_Category = p.HomeCareLibrary_Category
                                   }).ToList();
            model.listPortfolioTags = (from p in db.Features
                                       select new HomeCareModel()
                                       {
                                           CategoryID = p.categoryID,
                                           Feature_code = p.feature_code.Trim(),
                                           Feature_Name = p.feature_name,
                                           Feature_description = p.feature_description,
                                           feature_url = p.feature_url
                                       }).ToList();
            return View(model);

        }
        public ActionResult overview(string Id)
        {

            

            //Session[SessionConstants.PROMO_CODE] = 123;


            var model = new OverviewModel();
            try
            {
                model = (from p in db.HCL_Overview
                         join f in db.Features on p.feature_code equals f.feature_code
                         join rc in db.RC_Task_Details on f.feature_code equals rc.feature_code
                         join qa in db.HCL_QA_Urls on f.feature_code equals qa.feature_code
                         where f.feature_name == Id.Replace("-", " ")
                         orderby qa.qa_topic_order ascending
                         select new OverviewModel()
                         {
                             feature_code = p.feature_code.Trim(),

                             overview_content = p.overview_content,
                             overview_ImageURL = p.overview_imageURL,
                             overview_URL = p.overview_url,
                             Feature_name = f.feature_name.Trim(),
                             meta_description = p.overview_meta_desc,
                             meta_key = p.overview_meta_thumb,
                             rc_task_content = rc.rc_task_content,
                             qa_topic = qa.qa_topic

                         }).FirstOrDefault();

            }
            catch { }

            if (Request.IsAjaxRequest())
                return PartialView("overviewPartial", model);
            else
                return View(model);
        }
        public ActionResult care(string Id, string featureId)
        {

           

            //Session[SessionConstants.PROMO_CODE] = 123;

            var model = new careModel();
            try
            {

                if (featureId == null)
                {
                    model = (from p in db.RC_Task_Details
                             join f in db.Features on p.feature_code equals f.feature_code
                             join o in db.HCL_Tasks on p.feature_code equals o.feature_code
                             join qa in db.HCL_QA_Urls on p.feature_code equals qa.feature_code
                             where f.feature_name == Id.Replace("-", " ")
                             orderby qa.qa_topic_order ascending
                             select new careModel()
                             {
                                 feature_code = p.feature_code.Trim(),
                                 Feature_name = f.feature_name,
                                 task_code = p.task_code.Trim(),
                                 Display_icon_code = p.display_icon_code,
                                 rc_task_title = p.rc_task_title,
                                 rc_task_content = p.rc_task_content,
                                 rc_rec_timing = p.rc_rec_timing,
                                 rc_priority = p.rc_priority,
                                 rc_type = p.rc_type,
                                 rc_benefit_content = p.rc_benefit_content,
                                 rc_energy_saving_score = p.rc_energy_savings_score,
                                 rc_energy_saving_content = p.rc_energy_savings_content,
                                 rc_cost_score = p.rc_cost_score,
                                 rc_cost_content = p.rc_cost_content,
                                 rc_more_info_link = p.rc_more_info_link,
                                 rc_knowledge_level = p.rc_knowledge_level,
                                 rc_cycle_timing = p.rc_cycle_timing,
                                 rc_timing_months = p.rc_timing_months,
                                 rc_task_order = p.rc_task_order,
                                 rc_task_url = p.rc_task_url,
                                 rc_task_description = p.rc_task_description,
                                 rc_excluded_features = p.rc_excluded_features,
                                 task_intro = o.task_intro,
                                 task_howto_image = o.task_howto_imageURL,
                                 task_howto = o.task_howto,
                                 task_benefits_full = o.task_benefits_full,
                                 task_ensav_full = o.task_ensav_full,
                                 task_costs_full = o.task_costs_full,
                                 task_meta_desc = o.task_meta_desc,
                                 task_meta_key = o.task_meta_key,
                                 qa_topic = qa.qa_topic
                             }).FirstOrDefault();



                    var getPortfolioDescriptionId2 = (from p in db.RC_Task_Details where p.feature_code == Id select p.task_code).FirstOrDefault();

                    model.listRoutine = (from p in db.RC_Task_Details
                                         join f in db.Features on p.feature_code equals f.feature_code
                                         where f.feature_name == Id.Replace("-", " ") && p.task_code != getPortfolioDescriptionId2

                                         select new careModel()
                                         {

                                             feature_code = p.feature_code.Trim(),
                                             Feature_name = f.feature_name,
                                             task_code = p.task_code.Trim(),
                                             Display_icon_code = p.display_icon_code,
                                             rc_task_title = p.rc_task_title,
                                             rc_task_content = p.rc_task_content,
                                             rc_rec_timing = p.rc_rec_timing,
                                             rc_priority = p.rc_priority,
                                             rc_type = p.rc_type,
                                             rc_benefit_content = p.rc_benefit_content,
                                             rc_energy_saving_score = p.rc_energy_savings_score,
                                             rc_energy_saving_content = p.rc_energy_savings_content,
                                             rc_cost_score = p.rc_cost_score,
                                             rc_cost_content = p.rc_cost_content,
                                             rc_more_info_link = p.rc_more_info_link,
                                             rc_knowledge_level = p.rc_knowledge_level,
                                             rc_cycle_timing = p.rc_cycle_timing,
                                             rc_timing_months = p.rc_timing_months,
                                             rc_task_order = p.rc_task_order,
                                             rc_task_url = p.rc_task_url,
                                             rc_task_description = p.rc_task_description,
                                             rc_excluded_features = p.rc_excluded_features,

                                         }).ToList();
                }
                else
                {
                    model = (from p in db.RC_Task_Details
                             join f in db.Features on p.feature_code equals f.feature_code
                             join o in db.HCL_Tasks on p.task_code equals o.task_code
                             join qa in db.HCL_QA_Urls on p.feature_code equals qa.feature_code
                             join b in db.RC_Task_Benefits on p.task_code equals b.task_code
                             where p.rc_task_content == featureId.Replace("-", " ")
                             orderby qa.qa_topic_order ascending
                             select new careModel()
                             {
                                 feature_code = p.feature_code.Trim(),
                                 Feature_name = f.feature_name,
                                 task_code = p.task_code.Trim(),
                                 Display_icon_code = p.display_icon_code,
                                 rc_task_title = p.rc_task_title,
                                 rc_task_content = p.rc_task_content,
                                 rc_rec_timing = p.rc_rec_timing,
                                 rc_priority = p.rc_priority,
                                 rc_type = p.rc_type,
                                 rc_benefit_content = p.rc_benefit_content,
                                 rc_energy_saving_score = p.rc_energy_savings_score,
                                 rc_energy_saving_content = p.rc_energy_savings_content,
                                 rc_cost_score = p.rc_cost_score,
                                 rc_cost_content = p.rc_cost_content,
                                 rc_more_info_link = p.rc_more_info_link,
                                 rc_knowledge_level = p.rc_knowledge_level,
                                 rc_cycle_timing = p.rc_cycle_timing,
                                 rc_timing_months = p.rc_timing_months,
                                 rc_task_order = p.rc_task_order,
                                 rc_task_url = p.rc_task_url,
                                 rc_task_description = p.rc_task_description,
                                 rc_excluded_features = p.rc_excluded_features,
                                 task_intro = o.task_intro,
                                 task_howto_image = o.task_howto_imageURL,
                                 task_howto = o.task_howto,
                                 task_benefits_full = o.task_benefits_full,
                                 task_ensav_full = o.task_ensav_full,
                                 task_costs_full = o.task_costs_full,
                                 task_meta_desc = o.task_meta_desc,
                                 task_meta_key = o.task_meta_key,
                                 qa_topic = qa.qa_topic,
                                 benifits_image = b.tbr_web_display_order
                             }).FirstOrDefault();


                    model.listRoutine = (from p in db.RC_Task_Details
                                         join f in db.Features on p.feature_code equals f.feature_code
                                         where f.feature_name == Id.Replace("-", " ") && p.rc_task_content != featureId.Replace("-", " ")

                                         select new careModel()
                                         {
                                             feature_code = p.feature_code.Trim(),
                                             Feature_name = f.feature_name,
                                             task_code = p.task_code.Trim(),
                                             Display_icon_code = p.display_icon_code,
                                             rc_task_title = p.rc_task_title,
                                             rc_task_content = p.rc_task_content,
                                             rc_rec_timing = p.rc_rec_timing,
                                             rc_priority = p.rc_priority,
                                             rc_type = p.rc_type,
                                             rc_benefit_content = p.rc_benefit_content,
                                             rc_energy_saving_score = p.rc_energy_savings_score,
                                             rc_energy_saving_content = p.rc_energy_savings_content,
                                             rc_cost_score = p.rc_cost_score,
                                             rc_cost_content = p.rc_cost_content,
                                             rc_more_info_link = p.rc_more_info_link,
                                             rc_knowledge_level = p.rc_knowledge_level,
                                             rc_cycle_timing = p.rc_cycle_timing,
                                             rc_timing_months = p.rc_timing_months,
                                             rc_task_order = p.rc_task_order,
                                             rc_task_url = p.rc_task_url,
                                             rc_task_description = p.rc_task_description,
                                             rc_excluded_features = p.rc_excluded_features
                                         }).ToList();
                }
            }
            catch { }
            if (Request.IsAjaxRequest())
                return PartialView("carePartial", model);
            else
                return View(model);
        }
        public ActionResult questions(string Id, string featureId)
        {

           

            //Session[SessionConstants.PROMO_CODE] = 123;


            var model = new questionsModel();
            try
            {
                if (featureId == null)
                {
                    model = (from p in db.HCL_QA_Urls
                             join f in db.Features on p.feature_code equals f.feature_code
                             where f.feature_name == Id.Replace("-", " ")
                             select new questionsModel()
                             {
                                 feature_code = p.feature_code.Trim(),
                                 Feature_name = f.feature_name,
                                 qa_topic_order = p.qa_topic_order,
                                 qa_topic_code = p.qa_topic_code,
                                 qa_topic = p.qa_topic,
                                 qa_topic_intro = p.qa_topic_intro,
                                 qa_image_url = p.qa_image_url,
                                 qa_topic_url = p.qa_topic_url,
                                 qa_topic_meta_desc = p.qa_topic_meta_desc,
                                 qa_topic_meta_key = p.qa_topic_meta_thumb,


                             }).FirstOrDefault();
                    var getPortfolioDescriptionId = (from p in db.HCL_QA_Urls join f in db.Features on p.feature_code equals f.feature_code where f.feature_name == Id.Replace("-", " ") select p.qa_topic_code).FirstOrDefault();
                    model.listQ_A = (from p in db.HCL_QA_Contents
                                     where p.qa_topic_code == getPortfolioDescriptionId
                                     select new Q_AUrlModel()
                                          {
                                              qa_topic_code = p.qa_topic_code.Trim(),
                                              qa_qa_order = p.qa_qa_order,
                                              qa_followon_order = p.qa_followon_order,
                                              qa_question = p.qa_question,
                                              qa_answer = p.qa_answer,

                                          }).ToList();
                    var getPortfolioDescriptionId2 = (from p in db.HCL_QA_Urls join f in db.Features on p.feature_code equals f.feature_code where f.feature_name == Id.Replace("-", " ") select p.qa_topic_code).FirstOrDefault();
                    model.listQ_AContent = (from p in db.HCL_QA_Urls
                                            join f in db.Features on p.feature_code equals f.feature_code
                                            where f.feature_name == Id.Replace("-", " ") && p.qa_topic_code != getPortfolioDescriptionId2
                                            select new questionsModel()
                                            {
                                                feature_code = p.feature_code.Trim(),
                                                qa_topic_order = p.qa_topic_order,
                                                qa_topic_code = p.qa_topic_code.Trim(),
                                                qa_topic = p.qa_topic,
                                                qa_topic_intro = p.qa_topic_intro,
                                                qa_image_url = p.qa_image_url,
                                                qa_topic_url = p.qa_topic_url,
                                                qa_topic_meta_desc = p.qa_topic_meta_desc,
                                                qa_topic_meta_key = p.qa_topic_meta_thumb,
                                                Feature_name = f.feature_name

                                            }).ToList();
                }
                else
                {
                    model = (from p in db.HCL_QA_Urls
                             join f in db.Features on p.feature_code equals f.feature_code
                             join rc in db.RC_Task_Details on f.feature_code equals rc.feature_code
                             where f.feature_name == Id.Replace("-", " ") && p.qa_topic == featureId.Replace("-", " ")

                             select new questionsModel()
                             {
                                 feature_code = p.feature_code.Trim(),
                                 qa_topic_order = p.qa_topic_order,
                                 qa_topic_code = p.qa_topic_code.Trim(),
                                 qa_topic = p.qa_topic,
                                 qa_topic_intro = p.qa_topic_intro,
                                 qa_image_url = p.qa_image_url,
                                 qa_topic_url = p.qa_topic_url,
                                 qa_topic_meta_desc = p.qa_topic_meta_desc,
                                 qa_topic_meta_key = p.qa_topic_meta_thumb,
                                 Feature_name = f.feature_name,
                                 rc_task_content = rc.rc_task_content,
                             }).FirstOrDefault();
                    var topicCode = (from p in db.HCL_QA_Urls where p.qa_topic == featureId.Replace("-", " ") select p.qa_topic_code).FirstOrDefault();
                    model.listQ_A = (from p in db.HCL_QA_Contents

                                     where p.qa_topic_code == topicCode
                                     orderby p.qa_qa_order ascending
                                     select new Q_AUrlModel()
                                     {


                                         qa_topic_code = p.qa_topic_code.Trim(),
                                         qa_qa_order = p.qa_qa_order,
                                         qa_followon_order = p.qa_followon_order,
                                         qa_question = p.qa_question,
                                         qa_answer = p.qa_answer,

                                     }).ToList();
                    model.listQ_AContent = (from p in db.HCL_QA_Urls
                                            join f in db.Features on p.feature_code equals f.feature_code
                                            where f.feature_name == Id.Replace("-", " ") && p.qa_topic != featureId.Replace("-", " ")
                                            select new questionsModel()
                                            {
                                                feature_code = p.feature_code.Trim(),
                                                qa_topic_order = p.qa_topic_order,
                                                qa_topic_code = p.qa_topic_code.Trim(),
                                                qa_topic = p.qa_topic,
                                                qa_topic_intro = p.qa_topic_intro,
                                                qa_image_url = p.qa_image_url,
                                                qa_topic_url = p.qa_topic_url,
                                                qa_topic_meta_desc = p.qa_topic_meta_desc,
                                                qa_topic_meta_key = p.qa_topic_meta_thumb,
                                                Feature_name = f.feature_name

                                            }).ToList();
                }
            }
            catch { }
            if (Request.IsAjaxRequest())
                return PartialView("questionsPartial", model);
            else
                return View(model);

        }
        public ActionResult articles(string Id, string featureId)
        {

          
           

            //Session[SessionConstants.PROMO_CODE] = 123;
            if (featureId == "" || featureId == null)

            {
                var model = new ArticlesModel();
                try
                {
                    model = (from d in db.HCL_Article_Displays
                             join a in db.HCL_Article_Details on d.article_code equals a.article_code
                             join f in db.Features on d.feature_code equals f.feature_code
                             join rc in db.RC_Task_Details on f.feature_code equals rc.feature_code
                             join qa in db.HCL_QA_Urls on f.feature_code equals qa.feature_code
                             where f.feature_name == Id.Replace("-", " ")
                             orderby qa.qa_topic_order ascending
                             select new ArticlesModel()
                             {
                                 

                                 feature_code = f.feature_code.Trim(),
                                 article_code = a.article_code.Trim(),
                                 article_title = a.article_title,
                                 article_summary = a.article_summary,
                                 article_small_image_icon = a.article_small_image_url,
                                 article_big_image = a.article_big_image,
                                 article_bottom_content = a.article_bottom_content,
                                 article_top_content = a.article_top_content,
                                 article_video = a.article_video,
                                 article_Url = a.article_url,
                                 Feature_name = f.feature_name,
                                 article_meta_desc = a.article_meta_desc,
                                 article_meta_key = a.article_meta_thumb,
                                 rc_task_content = rc.rc_task_content,
                                 qa_topic = qa.qa_topic
                             }).FirstOrDefault();



                    //Get portfolioDescriptionID

                    model.listArtical = (from d in db.HCL_Article_Displays
                                         join a in db.HCL_Article_Details on d.article_code equals a.article_code
                                         join f in db.Features on d.feature_code equals f.feature_code
                                         where f.feature_name == Id.Replace("-", " ")
                                         select new ArticlesModel()
                                          {
                                              feature_code = f.feature_code.Trim(),
                                              article_code = a.article_code.Trim(),
                                              article_title = a.article_title,
                                              article_summary = a.article_summary,
                                              article_small_image_icon = a.article_small_image_url,
                                              article_big_image = a.article_big_image,
                                              article_bottom_content = a.article_bottom_content,
                                              article_top_content = a.article_top_content,
                                              article_video = a.article_video,
                                              Feature_name = f.feature_name,
                                              article_meta_desc = a.article_meta_desc,
                                              article_meta_key = a.article_meta_thumb
                                          }).ToList();
                }
                catch { }
                if (Request.IsAjaxRequest())
                    return PartialView("articlesPartial", model);
                else
                    return View(model);
            }
            else
            {
                var model = new ArticlesModel();
                try
                {
                    var articleCode = (from d in db.HCL_Article_Details where d.article_title == featureId.Replace("-", " ") select d.article_code).FirstOrDefault();
                    model = (from d in db.HCL_Article_Displays
                             join a in db.HCL_Article_Details on d.article_code equals a.article_code
                             join f in db.Features on d.feature_code equals f.feature_code
                             join rc in db.RC_Task_Details on f.feature_code equals rc.feature_code
                             join qa in db.HCL_QA_Urls on f.feature_code equals qa.feature_code
                             where d.article_code == articleCode && f.feature_name == Id.Replace("-", " ")
                             orderby qa.qa_topic_order ascending
                             select new ArticlesModel()
                             {
                                 feature_code = f.feature_code.Trim(),
                                 article_code = a.article_code.Trim(),
                                 article_title = a.article_title,
                                 article_summary = a.article_summary,
                                 article_small_image_icon = a.article_small_image_url,
                                 article_big_image = a.article_big_image,
                                 article_bottom_content = a.article_bottom_content,
                                 article_top_content = a.article_top_content,
                                 article_video = a.article_video,
                                 article_Url = a.article_url,
                                 Feature_name = f.feature_name,
                                 article_meta_desc = a.article_meta_desc,
                                 article_meta_key = a.article_meta_thumb,
                                 rc_task_content = rc.rc_task_content,
                                 qa_topic = qa.qa_topic
                             }).FirstOrDefault();

                    //Get portfolioDescriptionID
                    //var getPortfolioDescriptionId = (from p in db.Features where p.ID == ID select p.ID).FirstOrDefault();
                    model.listArtical = (from d in db.HCL_Article_Displays
                                         join a in db.HCL_Article_Details on d.article_code equals a.article_code
                                         join f in db.Features on d.feature_code equals f.feature_code
                                         where f.feature_name == Id.Replace("-", " ") && d.article_code != articleCode
                                         select new ArticlesModel()
                                         {
                                             feature_code = f.feature_code.Trim(),
                                             article_code = a.article_code.Trim(),
                                             article_title = a.article_title,
                                             article_summary = a.article_summary,
                                             article_small_image_icon = a.article_small_image_url,
                                             article_big_image = a.article_big_image,
                                             article_bottom_content = a.article_bottom_content,
                                             article_top_content = a.article_top_content,
                                             article_video = a.article_video,
                                             Feature_name = f.feature_name,
                                             article_meta_desc = a.article_meta_desc,
                                             article_meta_key = a.article_meta_thumb
                                         }).ToList();
                }
                catch { }
                if (model.article_video == null)
                    if (Request.IsAjaxRequest())
                        return PartialView("articalesdetailPartial", model);
                    else
                        return View("ArticleDetail", model);
                else
                    if (Request.IsAjaxRequest())
                        return PartialView("articlevideosPartial", model);
                    else
                        return View("ArticleDetailVideo", model);
            }
        }
        public ActionResult ArticleDetail(string Id, string featureId)
        {
            var model = new ArticlesModel();
            try
            {
                model = (from d in db.HCL_Article_Displays
                         join a in db.HCL_Article_Details on d.article_code equals a.article_code
                         join f in db.Features on d.feature_code equals f.feature_code
                         where d.article_code == Id && f.feature_code == featureId
                         select new ArticlesModel()
                         {
                             feature_code = f.feature_code.Trim(),
                             article_code = a.article_code.Trim(),
                             article_title = a.article_title,
                             article_summary = a.article_summary,
                             article_small_image_icon = a.article_small_image_url,
                             article_big_image = a.article_big_image,
                             article_bottom_content = a.article_bottom_content,
                             article_top_content = a.article_top_content,
                             article_video = a.article_video,
                             article_Url = a.article_url,
                             Feature_name = f.feature_name,
                             article_meta_desc = a.article_meta_desc,
                             article_meta_key = a.article_meta_thumb
                         }).FirstOrDefault();


                model.listArtical = (from d in db.HCL_Article_Displays
                                     join a in db.HCL_Article_Details on d.article_code equals a.article_code
                                     join f in db.Features on d.feature_code equals f.feature_code
                                     where f.feature_code == featureId && d.article_code != Id
                                     select new ArticlesModel()
                                     {
                                         feature_code = f.feature_code.Trim(),
                                         article_code = a.article_code.Trim(),
                                         article_title = a.article_title,
                                         article_summary = a.article_summary,
                                         article_small_image_icon = a.article_small_image_url,
                                         article_big_image = a.article_big_image,
                                         article_bottom_content = a.article_bottom_content,
                                         article_top_content = a.article_top_content,
                                         article_video = a.article_video,
                                         Feature_name = f.feature_name,
                                         article_meta_desc = a.article_meta_desc,
                                         article_meta_key = a.article_meta_thumb
                                     }).ToList();
            }
            catch { }
            return View(model);
        }
        public ActionResult ArticleDetailVideo(string Id, string featureId)
        {
            var model = new ArticlesModel();
            try
            {
                model = (from d in db.HCL_Article_Displays
                         join a in db.HCL_Article_Details on d.article_code equals a.article_code
                         join f in db.Features on d.feature_code equals f.feature_code
                         where d.article_code == Id && f.feature_code == featureId
                         select new ArticlesModel()
                         {
                             feature_code = f.feature_code.Trim(),
                             article_code = a.article_code.Trim(),
                             article_title = a.article_title,
                             article_summary = a.article_summary,
                             article_small_image_icon = a.article_small_image_url,
                             article_big_image = a.article_big_image,
                             article_bottom_content = a.article_bottom_content,
                             article_top_content = a.article_top_content,
                             article_video = a.article_video,
                             article_Url = a.article_url,
                             Feature_name = f.feature_name,
                             article_meta_desc = a.article_meta_desc,
                             article_meta_key = a.article_meta_thumb
                         }).FirstOrDefault();

                //Get portfolioDescriptionID
                //var getPortfolioDescriptionId = (from p in db.Features where p.ID == ID select p.ID).FirstOrDefault();
                model.listArtical = (from d in db.HCL_Article_Displays
                                     join a in db.HCL_Article_Details on d.article_code equals a.article_code
                                     join f in db.Features on d.feature_code equals f.feature_code
                                     where f.feature_code == featureId && d.article_code != Id
                                     select new ArticlesModel()
                                     {
                                         feature_code = f.feature_code.Trim(),
                                         article_code = a.article_code.Trim(),
                                         article_title = a.article_title,
                                         article_summary = a.article_summary,
                                         article_small_image_icon = a.article_small_image_url,
                                         article_big_image = a.article_big_image,
                                         article_bottom_content = a.article_bottom_content,
                                         article_top_content = a.article_top_content,
                                         article_video = a.article_video,
                                         Feature_name = f.feature_name,
                                         article_meta_desc = a.article_meta_desc,
                                         article_meta_key = a.article_meta_thumb
                                     }).ToList();
            }
            catch { }
            return View(model);
        }
        //[ChildActionOnly]
        public ActionResult DisplayUserName(int Id)
        {
            var model = new SponsorInputs345xModel();

            model = (from u in db.SponsorInputs345x
                     where u.Sponsor_ID == Id
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = u.Sponsor_ID,
                         spon_pic = u.Spon_Pic,
                         spon_logo = u.Spon_Logo,
                         spon_logo_tag = u.Spon_Logo_Tag,
                         spon_yourname = u.Spon_YourName,
                         spon_phoneban = u.Spon_PhoneBan,
                         spon_email = u.Spon_Email,
                         spon_web_add = u.Spon_Web_Add


                     }).FirstOrDefault();

            return PartialView("Partial1", model);
        }
        public ActionResult menu()
        {


            var model = new MainMenuModel();

            model.listCategory = (from p in db.HomeCareLibraryCategories
                                  select new MainMenuModel()
                                  {
                                      ID = p.ID,
                                      HomeCare_Category = p.HomeCareLibrary_Category
                                  }).ToList();
            model.listSubCategory = (from p in db.Features
                                     select new SubmenuModel()
                                     {
                                         CategoryID = p.categoryID,
                                         Feature_code = p.feature_code.Trim(),
                                         Feature_Name = p.feature_name,
                                         Feature_description = p.feature_description,
                                         feature_url = p.feature_url
                                     }).ToList();
            return PartialView("menu", model);

        }
        public ActionResult UserDetails(int Id)
        {
            var model = new SponsorInputs345xModel();

            model = (from u in db.SponsorInputs345x
                     where u.Sponsor_ID == Id
                     select new SponsorInputs345xModel()
                     {
                         Sponsor_ID = u.Sponsor_ID,
                         spon_pic = u.Spon_Pic,
                         spon_logo = u.Spon_Logo,
                         spon_logo_tag = u.Spon_Logo_Tag,
                         spon_yourname = u.Spon_YourName,
                         spon_phoneban = u.Spon_PhoneBan,
                         spon_email = u.Spon_Email,
                         spon_web_add = u.Spon_Web_Add
                     }).FirstOrDefault();

            return PartialView("UserDetails", model);
        }

        public ActionResult Welcome()
        {
            return View();
        }


        // [HttpPost]
        public ActionResult Tasks(string userId)
        {
            Session[SessionConstants.USER_ID] = 123;

            ViewBag.SelectedTask = "Tasks";
            return View("Welcome");
        }

        //  [HttpPost]
        public ActionResult Tips(string userId)
        {
            Session[SessionConstants.USER_ID] = 123;

            ViewBag.SelectedTask = "Tips";
            return View("Welcome");
        }


        //  [HttpPost]
        public ActionResult Ideas(string userId)
        {


            Session[SessionConstants.USER_ID] = 123;

            ViewBag.SelectedTask = "Ideas";
            return View("Welcome");
        }


        public ActionResult Login(string returnUrl)
        {

            ViewBag.getUserSessionId = TempData["getUserSessionId"];


            ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

            string str = null;
            foreach (string key in Session.Keys)
            {
                try
                {
                    if (Session[key] != null)
                    {

                        str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                    }
                }
                catch
                { }
            }
            ViewBag.getSession = str;

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;


            ViewBag.errorMessage = TempData["Error"];

            ViewBag.ReturnURL = returnUrl;

            ViewBag.CheckLogOut = TempData["checkLogOut"];

            return View();
        }

        [HttpPost]
        public ActionResult Login(LoginWebModel model)
        {
            DataRepository entities = new DataRepository();
            var getResult = entities.login_Result(model.ParamUserName, model.ParamPassword);

           
            ////return Json(new { JsonResult = getResult }, JsonRequestBehavior.AllowGet);
            var result = getResult.FirstOrDefault();
            // if (result.WebLogin == "validLoginActivePC")
            if (result.WebLogin == null && result.WebSetup == "usernameEmpty")
            {
                ViewBag.InvalidLogin = "Username is required";
            }
            else if (result.WebLogin == null && result.WebSetup == "passwordEmpty")
            {
                ViewBag.InvalidLogin = "Password is required";
            }
            else if (result.WebLogin == "invalidUsername" || result.WebLogin == "invalidPassword")
            {
                ViewBag.InvalidLogin = "Entered username/password is invalid.";
            }
            else
            {
                // Update session userid
                Session[SessionConstants.USER_ID] = result.user_id;
                Session[SessionConstants.PROMO_CODE] = result.sponsor;
                Session[SessionConstants.USER_NAME] = model.ParamUserName;
                //Session[SessionConstants.MODE] = ApplicationModeConstants.IPHONE_APP; //Only for Testing
                // get the sponsor code from logged in user or session. (Will be already updated in session from the BaseController)
                var sponsorCode = !string.IsNullOrEmpty(result.sponsor) ? result.sponsor : Session[SessionConstants.PROMO_CODE] as string;
                if (!string.IsNullOrEmpty(sponsorCode))
                {
                    // check for sponsor code valid
                    if (!string.IsNullOrWhiteSpace(sponsorCode))
                    {
                        var sponsorService = new SponsorAppService();
                        var checkSponsorResult = sponsorService.CheckPromoCode(new CheckPromocodeRequest
                        {
                            PromoCode = sponsorCode
                        });

                        sponsorCode = string.Empty;

                        if (checkSponsorResult == null || !checkSponsorResult.Any() || checkSponsorResult.First().PromocodeCheck == "nothingSent")
                        {
                            // invalid promo code, need to show invalid code warning
                            ViewBag.SponsorCodeCheck = "Invalid";
                        }
                        else
                        {
                            // Set the view bag with promocode chcek result.
                            var promoCodeResult = checkSponsorResult.First();
                            ViewBag.SponsorCodeCheck = promoCodeResult.PromocodeCheck;
                              // check if valid sponsor
                           
                            if (promoCodeResult.PromocodeCheck == "foundInactive")
                            {
                                // inactive sponsor, null out session data.
                                //Session[SessionConstants.PROMO_CODE] = null;
                                Session[SessionConstants.PROMO_CODE] = promoCodeResult.promocode;
                                Session[SessionConstants.IS_PROMO_CODE_ACTIVE] = promoCodeResult.PromocodeCheck;
                            }
                            else
                            {
                                sponsorCode = promoCodeResult.promocode;

                                // update sponsor 345x input format data to session which will be used by most of the pages for updating the sponsor logo and other features
                                var sponsorSessionData = sponsorService.GetSponsorInput345xData(promoCodeResult.promocode);
                                Session[SessionConstants.SPONSOR_DETAILS] = sponsorSessionData;
                                
                                // check session promocode, if not already set or different update DB.
                                if (Session[SessionConstants.PROMO_CODE] == null || Session[SessionConstants.PROMO_CODE].ToString() != promoCodeResult.promocode)
                                {
                                    // Update DB.
                                    SponsorAppService service = new SponsorAppService();
                                    service.UpdateUserSponsorCode(result.user_id.Value, promoCodeResult.promocode);
                                }
                                
                                // Update session promocode.
                                Session[SessionConstants.PROMO_CODE] = promoCodeResult.promocode;
                                Session[SessionConstants.IS_PROMO_CODE_ACTIVE] = promoCodeResult.PromocodeCheck;

                            }
                        }
                    }
                }

                //comment on(5.2.2014)
                //var cookiesToStore = string.Format("id={0},name={1},promo={2}", result.user_id.Value.ToString(), model.ParamUserName, sponsorCode);
                //var authTicket = new FormsAuthenticationTicket(1, cookiesToStore, DateTime.Now, DateTime.Now.AddYears(1), false, model.ParamUserName);
                //string cookieContents = FormsAuthentication.Encrypt(authTicket);

                //var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
                //{
                //    Expires = authTicket.Expiration,
                //    Path = FormsAuthentication.FormsCookiePath
                //};

                //Response.Cookies.Add(cookie);

                //if (!string.IsNullOrEmpty(model.ReturnURL))
                //{
                //    if (Url.IsLocalUrl(model.ReturnURL))
                //    {
                //        return Redirect(model.ReturnURL);
                //    }
                //}

                return Redirect("/Home/Welcome");
            }

            return View();
        }

        private void ClearCookie(string cookieName)
        {
            if (this.Request.Cookies[cookieName] != null)
            {
                HttpCookie expireCookie = new HttpCookie(cookieName);
                expireCookie.Expires = DateTime.Now.AddYears(-1);
                Response.Cookies.Add(expireCookie);
            }
        }

        public ActionResult Initialsetup()
        {
            Session[SessionConstants.ACTIVITY_TYPE] = "initialSetup";
            return View();
        }

         [HttpPost]
        public ActionResult Initialsetup(InitialSetupModel model)
        {

            DataRepository entities = new DataRepository();
            var getResult = entities.Web_Initial_Setup_Result(model.paramUserName, model.paramPassword, model.paramPromoCode);
            var result = getResult.FirstOrDefault();

            if ((result.webSetup == "usernameEmpty") || (result.webSetup == "passwordEmpty"))
            {
                ViewBag.Message = "You have not entered a Username(or Password).";
            }

            else if (result.webSetup == "usernameTaken") //webSetup=”dupeUser”
            {
                ViewBag.Message = "Sorry, this username is already taken, please enter a different one.";
            }
            else if (result.webSetup == "invalidPromocode")
            {
                ViewBag.Message = "Promo Code not valid. Check and re-try, or delete.";
            }
            else if (result.webSetup == "newUserError")
            {
                ViewBag.Message = "Some error occur.";
            }
            else if (result.webSetup == "validUsernameInactivePC")
            {
                //set LocalStorage Objects for “sponsor data” (cookie)
                CreateNewCookie(Convert.ToInt32(result.user_id), model.paramUserName, model.paramPromoCode);
                Session[SessionConstants.SPONSOR_DETAILS] = null;
                Session[SessionConstants.PROMO_CODE] = null;
                Session[SessionConstants.ACTIVITY_TYPE]= ApplicationModeConstants.INITIAL_SETUP;
                return Redirect("/Personalization/Index");
            }
            else if (result.webSetup == "validUserNameWoPC")
            {
                //set LocalStorage Objects for “sponsor data” (cookie)
                CreateNewCookie(Convert.ToInt32(result.user_id), model.paramUserName, model.paramPromoCode);
                //clear “sponsor data” LocalStorage Objects
                Session[SessionConstants.SPONSOR_DETAILS] = null;
                Session[SessionConstants.PROMO_CODE] = null;
                 Session[SessionConstants.ACTIVITY_TYPE]=ApplicationModeConstants.INITIAL_SETUP;
                return Redirect("/Personalization/Index");
            }
            else if (result.webSetup == "validUsernameActivePC")
            {
                //set LocalStorage Objects for “sponsor data” (cookie)
                CreateNewCookie(Convert.ToInt32(result.user_id), model.paramUserName, model.paramPromoCode);
                Session[SessionConstants.ACTIVITY_TYPE] = ApplicationModeConstants.INITIAL_SETUP;
                return Redirect("/Personalization/Index");
            }
          
             return View();
        }


         public void CreateNewCookie(int userId, string paramUserName, string sponsor)
         {

             // Update session userid
             Session[SessionConstants.USER_ID] = userId;
             Session[SessionConstants.PROMO_CODE] = sponsor;
             Session[SessionConstants.USER_NAME] = paramUserName;

             // get the sponsor code from logged in user or session. (Will be already updated in session from the BaseController)
             var sponsorCode = !string.IsNullOrEmpty(sponsor) ? sponsor : Session[SessionConstants.PROMO_CODE] as string;
             if (!string.IsNullOrEmpty(sponsorCode))
             {
                 // check for sponsor code valid
                 if (!string.IsNullOrWhiteSpace(sponsorCode))
                 {
                     var sponsorService = new SponsorAppService();
                     var checkSponsorResult = sponsorService.CheckPromoCode(new CheckPromocodeRequest
                     {
                         PromoCode = sponsorCode
                     });

                     sponsorCode = string.Empty;

                     if (checkSponsorResult == null || !checkSponsorResult.Any() || checkSponsorResult.First().PromocodeCheck == "nothingSent")
                     {
                         // invalid promo code, need to show invalid code warning
                         ViewBag.SponsorCodeCheck = "Invalid";
                     }
                     else
                     {
                         // Set the view bag with promocode chcek result.
                         var promoCodeResult = checkSponsorResult.First();
                         ViewBag.SponsorCodeCheck = promoCodeResult.PromocodeCheck;
                         // check if valid sponsor
                         if (promoCodeResult.PromocodeCheck == "foundInactive")
                         {
                             // inactive sponsor, null out session data.
                             Session[SessionConstants.PROMO_CODE] = null;
                         }
                         else
                         {
                             sponsorCode = promoCodeResult.promocode;

                             // update sponsor 345x input format data to session which will be used by most of the pages for updating the sponsor logo and other features
                             var sponsorSessionData = sponsorService.GetSponsorInput345xData(promoCodeResult.promocode);
                             Session[SessionConstants.SPONSOR_DETAILS] = sponsorSessionData;

                             // check session promocode, if not already set or different update DB.
                             if (Session[SessionConstants.PROMO_CODE] == null || Session[SessionConstants.PROMO_CODE].ToString() != promoCodeResult.promocode)
                             {
                                 // Update DB.
                                 SponsorAppService service = new SponsorAppService();
                                 service.UpdateUserSponsorCode(userId, promoCodeResult.promocode);
                             }

                             // Update session promocode.
                             Session[SessionConstants.PROMO_CODE] = promoCodeResult.promocode;
                         }
                     }
                 }
             }
             //comment on(5.2.2014)
             //var cookiesToStore = string.Format("id={0},name={1},promo={2}", userId.ToString(), paramUserName, sponsorCode);
             //var authTicket = new FormsAuthenticationTicket(1, cookiesToStore, DateTime.Now, DateTime.Now.AddYears(1), false, paramUserName);
             //string cookieContents = FormsAuthentication.Encrypt(authTicket);

             //var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieContents)
             //{
             //    Expires = authTicket.Expiration,
             //    Path = FormsAuthentication.FormsCookiePath
             //};

             //Response.Cookies.Add(cookie);
             
         }


        public ActionResult About()
        {
            return View();
        }


         [HttpPost]
         public ActionResult LogOut()
         {
             var sponsorDetail = Session[HomeCareLibrary.Constants.SessionConstants.SPONSOR_DETAILS];
             var promocode = Session[HomeCareLibrary.Constants.SessionConstants.PROMO_CODE];
             Session.Clear();
             //Session.Abandon();
             Session.RemoveAll();
             //comment on(5.2.2014)
             //FormsAuthentication.SignOut();
             Session[HomeCareLibrary.Constants.SessionConstants.SPONSOR_DETAILS] = sponsorDetail;
             Session[HomeCareLibrary.Constants.SessionConstants.PROMO_CODE] = promocode;

           
             TempData["checkLogOut"] = "logout";
             return RedirectToAction("Login", "Home");
         }

         public ActionResult AskWizard()
         {

             ViewBag.sessionIds = "Session Id: " + Session.SessionID.ToString() + ", " + SessionConstants.USER_ID + "=" + Session[SessionConstants.USER_ID] + ", " + SessionConstants.USER_NAME + "=" + Session[SessionConstants.USER_NAME] + ", " + SessionConstants.PASSWORD + "=" + Session[SessionConstants.PASSWORD] + ", " + SessionConstants.MODE + "=" + Session[SessionConstants.MODE] + ", " + SessionConstants.ACTIVITY_TYPE + "=" + Session[SessionConstants.ACTIVITY_TYPE] + ", " + SessionConstants.PROMO_CODE + "=" + Session[SessionConstants.PROMO_CODE] + ", " + SessionConstants.SPONSOR_DETAILS + "=" + Session[SessionConstants.SPONSOR_DETAILS];

             string str = null;
             foreach (string key in Session.Keys)
             {
                 try
                 {
                     if (Session[key] != null)
                     {

                         str += string.Format("{0}: {1}<br />", key, Session[key].ToString());
                     }
                 }
                 catch
                 { }
             }
             ViewBag.getSession = str;
             
             
             Request.InputStream.Position = 0;
             StreamReader postedVariableStream = new StreamReader(Request.InputStream);
             string postedVariableJsonString = postedVariableStream.ReadToEnd();
             ViewBag.JsonString = postedVariableJsonString;

             string getContentType = Request.ContentType;
             ViewBag.ContentType = getContentType;

             string getRequestUrl = Request.Url.ToString();
             ViewBag.Url = getRequestUrl;


             return View();
         }

        [ActionName("Terms-Of-Use")]
         public ActionResult TermsOfUse()
         {
             //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing

             Request.InputStream.Position = 0;
             StreamReader postedVariableStream = new StreamReader(Request.InputStream);
             string postedVariableJsonString = postedVariableStream.ReadToEnd();
             ViewBag.JsonString = postedVariableJsonString;

             string getContentType = Request.ContentType;
             ViewBag.ContentType = getContentType;

             string getRequestUrl = Request.Url.ToString();
             ViewBag.Url = getRequestUrl;

             return View("Terms-Of-Use");
         }


        [ActionName("From-Another-Device")]
        public ActionResult FromAnotherDevice()
        {
            //Session[SessionConstants.MODE] = ApplicationModeConstants.IPHONE_APP; //Only for Testing

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            return View("From-Another-Device");
        }

        [ActionName("GetLoginInfo")]
        public ActionResult GetLoginInfo()
        {
            //Session[SessionConstants.MODE] = ApplicationModeConstants.ANDROID_APP; //Only for Testing

            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            return View("GetLoginInfo");
        
        }
        public ActionResult ForgotPassword()
        {
            Request.InputStream.Position = 0;
            StreamReader postedVariableStream = new StreamReader(Request.InputStream);
            string postedVariableJsonString = postedVariableStream.ReadToEnd();
            ViewBag.JsonString = postedVariableJsonString;

            string getContentType = Request.ContentType;
            ViewBag.ContentType = getContentType;

            string getRequestUrl = Request.Url.ToString();
            ViewBag.Url = getRequestUrl;

            return View("ForgotPassword");
        }
    }
}
